<script setup>
// import { useUserStore } from "@/store";
import router from "@/router";
import { ref } from "vue";
import { showToast, showConfirmDialog } from "@/utils/vant-ui";
import { THEME_COLORS, setTheme } from "@/utils/theme";
import { useUserStore } from "@/store";
import { updateUserInfoService } from "@/api/user";
const loading = ref(false);
const userStore = useUserStore();
const showThemePopup = ref(false);
// 新增密码相关变量
const showChangePasswordPopup = ref(false); // 第一步：验证当前密码弹窗
const showNewPasswordPopup = ref(false); // 第二步：设置新密码弹窗
const currentPassword = ref(""); // 当前密码输入
const newPassword = ref(""); // 新密码输入
const confirmPassword = ref(""); // 确认新密码输入
const onClickLeft = () => {
  router.go(-1);
};
const logout = () => {
  showConfirmDialog({
    title: "确认退出登录",
    message: "确定要退出登录吗？",
  })
    .then(() => {
      // 用户确认退出
      loading.value = true;
      // 清除token和user
      userStore.removeToken();
      userStore.removeUser();
      // 跳转到登录页面
      setTimeout(() => {
        loading.value = false;
        showToast("退出登录成功");
        router.push("/login");
      }, 2000);
    })
    .catch(() => {
      // 用户取消，不执行任何操作
    });
};
const selectTheme = (color) => {
  setTheme(color);
  showThemePopup.value = false;
  // 储存在本地
  localStorage.setItem("themeColor", color);
};
// 验证当前密码
const verifyCurrentPassword = () => {
  // 从 userStore 获取当前密码
  const storedPassword = userStore.user.userPasswd;

  if (!currentPassword.value) {
    showToast("请输入当前密码");
    return;
  }

  if (currentPassword.value !== storedPassword) {
    showToast("当前密码不正确");
    return;
  }

  // 验证通过，清空输入并打开新密码弹窗
  currentPassword.value = "";
  showChangePasswordPopup.value = false;
  showNewPasswordPopup.value = true;
};

// 修改密码
const changePassword = () => {
  // 新密码验证
  if (!newPassword.value) {
    showToast("请输入新密码");
    return;
  }

  if (newPassword.value.length < 6) {
    showToast("新密码长度至少为6位");
    return;
  }

  if (newPassword.value !== confirmPassword.value) {
    showToast("两次输入的新密码不一致");
    return;
  }

  // 确认修改
  showConfirmDialog({
    title: "确认修改密码",
    message: "修改后需要重新登录，确定要修改吗？",
  })
    .then(() => {
      updateUserInfoService({
        ...userStore.user,
        userPasswd: newPassword.value,
      }).then(() => {
        // 更新 store 中的密码
        userStore.setUser({
          ...userStore.user,
          userPasswd: newPassword.value,
        });
      });

      // 清空输入
      newPassword.value = "";
      confirmPassword.value = "";

      // 关闭弹窗并退出登录
      showNewPasswordPopup.value = false;
      showToast("密码修改成功，请重新登录");

      // 退出登录应清除token,和user
      setTimeout(() => {
        // 清除token和user
        userStore.removeToken();
        userStore.removeUser();
        // 跳转到登录页面
        router.push("/login");
        router.go(0);
      }, 0);
    })
    .catch(() => {
      // 用户取消
    });
};
</script>
<template>
  <div class="bigSetting">
    <div class="header">
      <van-nav-bar
        title="设置"
        left-arrow
        text-light
        @click-left="onClickLeft"
      />
    </div>
    <div class="main">
      <!-- 调整样式 -->
      <van-cell title="调整样式" is-link @click="showThemePopup = true" />
      <!-- 修改密码 -->
      <van-cell
        title="修改密码"
        is-link
        @click="showChangePasswordPopup = true"
      />
      <!-- 第一步：验证当前密码弹窗 -->
      <van-popup
        v-model:show="showChangePasswordPopup"
        position="bottom"
        :style="{ height: '30%' }"
        round
      >
        <div class="password-popup">
          <h3 class="popup-title">验证当前密码</h3>
          <van-field
            v-model="currentPassword"
            type="password"
            placeholder="请输入当前密码"
            :rules="[{ required: true, message: '密码不能为空' }]"
          />
          <div class="popup-footer">
            <van-button type="default" @click="showChangePasswordPopup = false"
              >取消</van-button
            >
            <van-button type="primary" @click="verifyCurrentPassword"
              >验证</van-button
            >
          </div>
        </div>
      </van-popup>

      <!-- 第二步：设置新密码弹窗 -->
      <van-popup
        v-model:show="showNewPasswordPopup"
        position="bottom"
        :style="{ height: '40%' }"
        round
      >
        <div class="password-popup">
          <h3 class="popup-title">设置新密码</h3>
          <van-field
            v-model="newPassword"
            type="password"
            placeholder="请输入新密码（至少6位）"
            clearable
            :rules="[{ min: 6, message: '密码至少6位' }]"
          />
          <van-field
            v-model="confirmPassword"
            type="password"
            placeholder="请确认新密码"
            clearable
          />
          <div class="popup-footer">
            <van-button type="default" @click="showNewPasswordPopup = false"
              >取消</van-button
            >
            <van-button type="primary" @click="changePassword"
              >确认修改</van-button
            >
          </div>
        </div>
      </van-popup>
      <!-- 底部弹窗（新增） -->
      <van-popup
        v-model:show="showThemePopup"
        position="bottom"
        :style="{ height: '40%' }"
        round
      >
        <div class="theme-popup">
          <h3 class="popup-title">选择主题颜色</h3>
          <div class="color-options">
            <div
              v-for="color in THEME_COLORS"
              :key="color.value"
              class="color-option"
              :style="{ backgroundColor: color.value }"
              @click="selectTheme(color.value)"
            >
              <span>{{ color.name }}</span>
            </div>
          </div>
        </div>
      </van-popup>
    </div>
    <!--退出登录按钮 -->
    <div class="logout">
      <van-button
        type="danger"
        size="large"
        @click="logout"
        round
        :loading="loading"
        >退出登录</van-button
      >
    </div>
  </div>
</template>
<style lang="less" scoped>
.bigSetting {
  height: 100%;
  background-color: rgb(247, 247, 249);
  font-size: 20px;
  .main {
    .theme-popup {
      padding: 20px;
      .popup-title {
        text-align: center;
        margin-bottom: 20px;
        font-size: 18px;
      }
      .color-options {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 15px;
        padding: 0 10px;
        .color-option {
          height: 50px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-weight: bold;
          box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
          &:active {
            transform: scale(0.95);
          }
        }
      }
    }
    .password-popup {
      padding: 20px;

      .popup-title {
        text-align: center;
        margin-bottom: 20px;
        font-size: 18px;
        font-weight: bold;
      }

      .van-field {
        margin-bottom: 15px;
        border-bottom: 1px solid #eee;

        &:last-child {
          border-bottom: none;
        }
      }

      .popup-footer {
        display: flex;
        gap: 15px;
        margin-top: 25px;

        .van-button {
          flex: 1;
          height: 40px;
          border-radius: 8px;

          &:first-child {
            background-color: #f5f5f5;
            color: #333;
          }
        }
      }
    }
  }
  .logout {
    display: flex;
    justify-content: center;
    width: 100%;
    padding: 20px;
  }
}
</style>
